import json


def load_data(file_path):
    with open(file_path, 'r') as f:
        data = json.load(f)
    return data


def validate_fractals(data):
    for i, entry in enumerate(data):
        if entry['top_fractal'] or entry['bottom_fractal']:
            left_distance = right_distance = float('inf')

            # Calculate left distance
            for j in range(i - 1, -1, -1):
                if data[j]['top_fractal'] or data[j]['bottom_fractal']:
                    left_distance = i - j
                    break

            # Calculate right distance
            for j in range(i + 1, len(data)):
                if data[j]['top_fractal'] or data[j]['bottom_fractal']:
                    right_distance = j - i
                    break

            if left_distance <= 3 and right_distance <= 3:
                if entry['top_fractal']:
                    entry['top_fractal'] = False
                if entry['bottom_fractal']:
                    entry['bottom_fractal'] = False

    return data


def process_fractals(data):
    # The data has already been validated and updated in validate_fractals
    return data


def save_data(data, output_file):
    with open(output_file, 'w') as f:
        json.dump(data, f, indent=4)


if __name__ == "__main__":
    input_file = '../static/initial_fractals_bnb_usdt_klines.json'
    output_file = '../static/processed_bnb_usdt_klines.json'

    kline_data = load_data(input_file)
    validated_data = validate_fractals(kline_data)
    processed_fractals = process_fractals(validated_data)
    save_data(processed_fractals, output_file)

    print(f"Processed fractals have been saved to {output_file}")
